package xyz.liut.onmyojihelper

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.support.v4.app.NotificationCompat
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import xyz.liut.onmyojihelper.runnable.ClickRunnable
import xyz.liut.onmyojihelper.runnable.TimeRunnable
import xyz.liut.onmyojihelper.util.GeneralHandler
import xyz.liut.onmyojihelper.util.LogUtil
import xyz.liut.onmyojihelper.view.FloatCtrlView
import xyz.liut.onmyojihelper.view.FloatShowView

@Suppress("DEPRECATION")
/**
 * OnmyojiHelper
 * </p>
 * Created by liut on 2017/10/31 0031.
 */
class CoreService : Service(), View.OnClickListener, GeneralHandler.HandlerMessage {

    companion object {
        private const val TAG = "CoreService"

        const val STATE_SHOW = 1
        const val STATE_END = 2

        const val HEART_BEATS = 200
    }

    private lateinit var ctrlView: FloatCtrlView
    private lateinit var showView: FloatShowView
    private lateinit var roundNumTv: TextView
    private lateinit var roundTimeTv: TextView

    private lateinit var clickRunnable: ClickRunnable
    private lateinit var clickThread: Thread

    private lateinit var timeRunnable: TimeRunnable

    private lateinit var handler: Handler

    private var roundNum = 15

    private var startTime: Long = 0
    private var state: Int = 0


    override fun onBind(p0: Intent?): IBinder {
        throw Exception("null")
    }

    override fun onCreate() {
        super.onCreate()

        initNotification()
        ctrlView = FloatCtrlView(this, this)
        ctrlView.show()
        showView = FloatShowView(this)
        showView.show()

        roundNumTv = showView.findViewById(R.id.round_num_tv)
        roundTimeTv = showView.findViewById(R.id.round_time_tv)
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        roundNum = intent!!.getIntExtra("roundNum", 15)
        val roundTime = intent.getIntExtra("roundTime", 70)
        val intervalTime = intent.getIntExtra("intervalTime", 5)

        handler = GeneralHandler(this)
        clickRunnable = ClickRunnable(handler,
                roundNum,
                roundTime.toDouble(),
                intervalTime.toDouble()
        )

        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * todo 置顶通知
     */
    private fun initNotification() {
        val notificationBuilder = NotificationCompat.Builder(this, "test")
        val notification = notificationBuilder.setContentText("---").setContentTitle("预留,功能待开发")
                .setSmallIcon(R.mipmap.ic_launcher).build()
        startForeground(1, notification)
        Log.d("MyService", "onCreate executed")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.start_bt -> {
                clickRunnable.roundNum = roundNum
                if (!clickRunnable.isRunning) {
                    clickThread = Thread(clickRunnable)
                    clickThread.start()
                }
            }
            R.id.stop_bt -> {
                clickRunnable.roundNum = 0
                showToast("stop")
            }
            R.id.close_bt -> {
                clickRunnable.roundNum = 0
                stopSelf()
            }
        }

    }


    @SuppressLint("SetTextI18n")
    override fun onMessage(msg: Message?) {
        when (msg?.what) {
            STATE_SHOW -> {
                state = STATE_SHOW
                startTime = System.currentTimeMillis()
                roundNumTv.text = "轮数: " + (roundNum - msg.arg1 + 1) + "/" + roundNum
                Toast.makeText(roundNumTv.context, "请开始你的表演", Toast.LENGTH_SHORT).show()

                timeRunnable = TimeRunnable(GeneralHandler(this), 5 * 60 * 10)
                Thread(timeRunnable).start()
            }

            STATE_END -> {
                state = STATE_END
                startTime = System.currentTimeMillis()
                Toast.makeText(roundNumTv.context, "结束战斗", Toast.LENGTH_SHORT).show()
                timeRunnable.time = 0
            }

            HEART_BEATS -> {
                val nowTime = System.currentTimeMillis() - startTime
                when (state) {
                    STATE_SHOW -> {
                        roundTimeTv.text = "表演: ${nowTime / 1000}/${clickRunnable.roundTimeFinal.toInt()}"
                    }
                    STATE_END -> {
                        roundTimeTv.text = "等待下局: ${nowTime / 1000}/${clickRunnable.intervalTimeFinal.toInt()}"
                    }
                }
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            try {
                clickRunnable.roundNum = 0
                clickThread.stop()
            } catch (e: Exception) {
                LogUtil.e(TAG, e.message.toString())
            }

            ctrlView.remove()
            showView.remove()

        } catch (e: Exception) {
            Log.e("liut", e.message, e)
        }
    }

    private fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }


}